#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from sheepomatic_io import Csv_file
from sheepomatic import Sheep,Shepherd

class Shepherd_adder:
   @classmethod
   def get_sheep2shepherd_hash(cls,couples):
      sheep2shepherd_key = {}
      for sheep_key,shepherd_key,happy,weight in couples:
         sheep2shepherd_key[sheep_key] = shepherd_key
      return sheep2shepherd_key

   @classmethod
   def get_shepherd2name_hash(cls,shepherds_list):
      # shepherd_key -> sheperd_name
      shepherd2name_hash = {}
      for shepherd in shepherds_list:
         shepherd2name_hash[shepherd.mail] = cls.shepherd2name(shepherd)
      return shepherd2name_hash

   @classmethod
   def shepherd2name(cls,shepherd):
      return shepherd.attr("Jméno a příjmení")
      
   @classmethod
   def read_couples(cls,filename):
      f = open(filename, 'r')
      couple_list = []
      #
      for line in f.readlines():
         line = line.strip()
         couple_list.append(tuple(line.split(",")))
      f.close()
      return couple_list

def main(args):
    # review parameters
    sheep_file = args[0]
    sheep_conf = args[1]
    shepherd_file = args[2]
    shepherd_conf = args[3]
    match_file = args[4]
    # read sheep + shepherds
    sheep_list = Csv_file.read_and_interpret_sheep_file(sheep_file,sheep_conf)
    shepherds_list = Csv_file.read_and_interpret_shepherd_file(shepherd_file,shepherd_conf)
    # read file with couples
    couples = Shepherd_adder.read_couples(match_file)
    sheep2shepherd_key = Shepherd_adder.get_sheep2shepherd_hash(couples)
    # read shepherd information
    shepherd2name_hash = Shepherd_adder.get_shepherd2name_hash(shepherds_list)
    # re-open and rewrite sheep file
    f = open(sheep_file, 'r')
    firstline = f.readline()
    firstline = firstline.strip()
    print "\"Tutor name\""+";"+"\"Tutor email\""+";"+firstline
    i=0
    for line in f.readlines():
       line = line.strip()
       if sheep_list[i].mail in sheep2shepherd_key:
          shepherd_mail = sheep2shepherd_key[sheep_list[i].mail]
          shepherd_name = shepherd2name_hash[shepherd_mail]
          print "\""+shepherd_name+"\""+";"+"\""+shepherd_mail+"\""+";"+line
       else:
          print "  ;;"+line 
       i=i+1

if __name__ == '__main__':
    args = sys.argv[1:]
    main(args)
